package com.yoomiito.app.ui.welcome;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.gyf.barlibrary.BarHide;
import com.gyf.barlibrary.ImmersionBar;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseActivity;
import com.yoomiito.app.Constant;
import com.yoomiito.app.MainActivity;
import com.yoomiito.app.R;
import com.yoomiito.app.base.WebViewActivity;
import com.yoomiito.app.model.bean.BannerAndIconInfo;
import com.yoomiito.app.model.config.SystemInfo;
import com.yoomiito.app.service.AppService;
import com.yoomiito.app.ui.push.UMManager;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.AllUtils;
import com.yoomiito.app.utils.CacheUtils;
import com.yoomiito.app.utils.ColorUtils;
import com.yoomiito.app.utils.Const;
import com.yoomiito.app.utils.DeviceConfigUtils;
import com.yoomiito.app.utils.EventMessage;
import com.yoomiito.app.utils.ImageUtils;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.ResUtil;
import com.yoomiito.app.utils.ShanYanUtils;
import com.yoomiito.app.utils.YMToast;
import com.yoomiito.app.utils.encrypt.JniUtils;
import com.yoomiito.app.utils.encrypt.StoreJni;
import com.yoomiito.app.widget.dialog.TipDialog;


import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.cache.SharedPref;

import cn.droidlover.xdroidmvp.router.Router;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class WelcomeActivity extends RxAppCompatActivity {

    @BindView(R.id.act_welcome_iv)
    ImageView mDefaultBgIv;
    @BindView(R.id.adIv)
    ImageView mAdIv;
    @BindView(R.id.toMain)
    TextView mToMainTv;

    private String token;
    private Disposable disposable;
    private boolean requesting = true;
    private String mPushMsg;
    public static final int DefaultTime = 3;
    private String mAdClickInfo;
    private TipDialog mTipDialog;//提示用户各种协议


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_BAR).init();
        Intent intent = getIntent();
        if (null != intent) {
            mPushMsg = getIntent().getStringExtra(Constant.UM_PUSH_MESSAGE);
            L.i("透传推送消息：" + mPushMsg);
        }
//        AllUtils.getDeviceInfo(this);
//        initConfig();
        boolean flag =  SharedPref.getInstance(App.getInstance()).getBoolean(Constant.IS_FIRST,false);
        if (flag) {//开启主页
            startWelcome(WelcomeActivity.DefaultTime, MainActivity.class);
        } else {//开启引导页
            if (SharedPref.getInstance(App.getInstance()).getBoolean(Const.Common.ShowUserPermissionTip, false)) {
                startWelcome(DefaultTime, SplashPagerActivity.class);
            } else {
                showUserPermissionTip();
            }
        }
    }


    public void showSystemInfo(SystemInfo systemInfo) {
        SystemInfoActivity.Companion.start(this, systemInfo);
        finish();
    }

    public void startWelcome(int time, Class cls) {
        disposable = Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(time + 1)
                .map((aLong -> time - aLong))
                .compose(bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(aLong -> {
                    L.i("倒计时");
                    if (mToMainTv != null) mToMainTv.setText("跳过" + aLong + "s");
                })
                .doOnComplete(() -> {
//                    dispose();
                    nextPage(cls);
                })
                .subscribe();
    }

    private void nextPage(Class cls) {
        Intent intent = new Intent(WelcomeActivity.this, cls);
        if (!TextUtils.isEmpty(mPushMsg)) {//不为空 则表示有离线推送消息透传过来  如果有离线推送消息透传过来 则一直传递到MainActivity
            intent.putExtra(Constant.UM_PUSH_MESSAGE, mPushMsg);
        }
        if (!TextUtils.isEmpty(mAdClickInfo)) {
            intent.putExtra(Constant.UM_PUSH_MESSAGE, mAdClickInfo);
        }
        startActivity(intent);
        finish();
    }

    public void showAd(BannerAndIconInfo bannerAndIconInfo) {
        if (bannerAndIconInfo == null ||
                TextUtils.isEmpty(bannerAndIconInfo.getImage_url()) ||
                (bannerAndIconInfo.getShow_type() == 2 && CacheUtils.INSTANCE.showed(Const.Common.ADShowType, bannerAndIconInfo))) {
            startWelcome(DefaultTime, MainActivity.class);
            return;
        }
        mAdIv.setOnClickListener(v -> {
            mAdClickInfo = JSONObject.toJSONString(bannerAndIconInfo);
//            dispose();
            nextPage(MainActivity.class);
        });

        Glide.with(this).asBitmap().load(bannerAndIconInfo.getImage_url()).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                L.i("原始资源: " + resource);
                L.i("屏幕宽高：" + App.mWidthPx + "  " + App.mHeightPx);
                L.i("原始宽高：" + resource.getWidth() + "  " + resource.getHeight());
                int screenWidth = App.mWidthPx;
                int bottomMargin = screenWidth * 120 / 375;
                int adHeight = App.mHeightPx - bottomMargin;//+DeviceConfigUtils.INSTANCE.getStatusBarHeight(WelcomeActivity.this)
                L.i("广告图宽高：" + adHeight + "  " + bottomMargin);

                FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mAdIv.getLayoutParams();
                lp.height = adHeight;
                mAdIv.setLayoutParams(lp);
                mAdIv.setVisibility(View.VISIBLE);
                Bitmap bitmap = ImageUtils.zoomBitmapFromWidth(resource, screenWidth);
                L.i("压缩后资源: " + bitmap);
                L.i("压缩后宽高：" + bitmap.getWidth() + "  " + bitmap.getHeight());
                Bitmap newBitmap = ImageUtils.cropBitmap(bitmap, (bitmap.getHeight() - adHeight));
                L.i("裁剪后资源: " + newBitmap);
                L.i("裁剪后宽高：" + newBitmap.getWidth() + "  " + newBitmap.getHeight());
                mAdIv.setImageBitmap(newBitmap);
                mToMainTv.setVisibility(View.VISIBLE);
                mToMainTv.setBackground(ColorUtils.INSTANCE.background(R.color.color_black_80, 13f));
                mToMainTv.setOnClickListener(v -> nextPage(MainActivity.class));
                startWelcome(bannerAndIconInfo.getShow_time(), MainActivity.class);
            }
        });
    }

    private void dispose() {
        if (disposable != null && !disposable.isDisposed()) disposable.dispose();
    }

    private void showUserPermissionTip() {
        if (mTipDialog == null) {
            mTipDialog = new TipDialog(this);
            mTipDialog.setTitle(ResUtil.getString(R.string.user_permission_tip_title));
            String spanTip1 = ResUtil.getString(R.string.user_permission_tip_click_text_1);
            String spanTip2 = ResUtil.getString(R.string.user_permission_tip_click_text_2);
//            mTipDialog.setTitleVisible(true);
            mTipDialog.setContentClick(ResUtil.getString(R.string.user_permission_tip_content), spanTip1, spanTip2);
            mTipDialog.setCancelText("不同意");
            mTipDialog.setSureText("同意");
            mTipDialog.setCanBack(false);
            mTipDialog.setCanceledOnTouchOutside(false);
            mTipDialog.setClickListener(v -> {
                SharedPref.getInstance(App.getInstance()).putBoolean(Const.Common.ShowUserPermissionTip, true);
                mTipDialog.dismiss();
//                Intent intent = new Intent(this, AppService.class);
//                intent.putExtra(Constant.TYPE, AllCode.Init);
//                startService(intent);
                UMManager.INSTANCE.initUm();
//                ShanYanUtils.INSTANCE.initShanYan(App.getInstance());
                startWelcome(DefaultTime, SplashPagerActivity.class);
            });
            mTipDialog.setmCancelClickListener(v -> {
                YMToast.showCenterToast("需要获得你的同意才能使用千年艾");
                finish();
            });
            mTipDialog.setmOnSpanTipClickListener(spanTip -> {
                if (spanTip1.equals(spanTip)) {
                    Router.newIntent(this)
                            .to(WebViewActivity.class)
                            .putInt(Constant.TYPE, Const.Url.UserAgreement)
                            .launch();
                } else if (spanTip2.equals(spanTip)) {
                    Router.newIntent(this)
                            .to(WebViewActivity.class)
                            .putInt(Constant.TYPE, Const.Url.PrivacyAgreement)
                            .launch();
                }
            });

        }
        mTipDialog.show();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTipDialog != null) {
            mTipDialog.dismiss();
        }
        ImmersionBar.with(this).destroy();
        dispose();
        System.gc();
    }
}
